#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: FlowReport.py
@Author: lijk34925 
@Date: 2024/5/20 20:05企业日志查询
@desc: 请补充本模块功能说明
"""
import os

import pandas as pd

from Plat.SeleniumPlatform import SeleniumPlatform
from BladeFerm.utils.basic_opration import get_TargetTime
from BladeFerm.utils.dataoperation import YamlOperation
from BladeFerm.Lib.Common import logger


class FlowReportObject:
    def __init__(self):
        self.download_path = None
        self.tables = None
        self.origin_execl = None
        self.report_config = {}
        self.platform = None
        self.platformConfig = None
        self.config = None
        # self.load_config(path)
        self.tables_number = 1
        self.tables_count = 0

    def load_config(self, path='./config/效能平台报表导出配置.yaml'):
        """
        加载配置
        :param path:
        :return:
        """
        self.tables_count = 0
        self.tables_number = 1
        self.config = YamlOperation(path).readYaml()
        self.platformConfig = self.config['platformConfig']
        cur_date = get_TargetTime(0, '%Y%m%d')
        self.download_path = self.platformConfig.get("downLoad", "./static/platfrom")
        self.download_path = self.download_path + '\\' + cur_date
        # clear_dir(self.download_path)     # 通过前端可以删除文件的
        self.platform = SeleniumPlatform(self.platformConfig, self.download_path)
        configuration_list = self.config['reportConfig']
        for report in configuration_list:
            self.report_config[report['displayName']] = report
        self.tables = self.config['tables']

    def download_tables(self, params: dict = None):
        """
        下载报表
        :param params: 更新用户名和密码
        :return:
        """
        self.load_config()
        cur_tables = params.get("tables", None)
        tables = cur_tables if cur_tables else self.tables
        self.tables_number = len(tables)
        self.platformConfig.update(params)
        self.platform.get_platform_session(self.platformConfig)
        self.platform.open_report_page()
        for index, table_name in enumerate(tables):
            config = self.report_config.get(table_name)
            try:
                self.platform.open_report(config['sourceName'])
                if config['sourceType'] == "layout":
                    self.platform.layout_download(config)
                elif config['sourceType'] == "frame":
                    self.platform.frame_download(config)
                else:
                    raise Exception(f"未知的报表来源类型{config['sourceType']}")
                self.platform.close_report(table_name)
            except Exception as e:
                logger.exception(f"error: {e}")
            self.tables_count = index + 1
        self.platform.close_browser()

    def query_origin_tables(self):
        if not self.report_config:
            self.load_config()
        cur_date = get_TargetTime(0, '%Y%m%d')
        return {"tables": list(self.report_config.keys()), "date": cur_date}

    def query_download_progress(self):
        """
        查询进度
        :return:
        """
        progress = round(self.tables_count / self.tables_number, 4) * 100
        tables = os.listdir(self.download_path)
        result = {"total": self.tables_number,
                  "count": self.tables_count,
                  "progress": progress,
                  "success": len(tables),
                  "fail": self.tables_count - len(tables),
                  "tables": tables}
        logger.info("Downloading progress: {}".format(result))
        return result

    def merge_tables(self, origin_table="", date='20240526', target_tables: list = None):
        origin_table_path = self.origin_execl if not origin_table else origin_table
        tables = self.tables if not target_tables else target_tables
        origin_file = pd.ExcelFile(origin_table_path, engine='openpyxl')
        for table in tables:
            table_path = f"./static/{date}/{table}.xlsx"
            # word_book = load_workbook(table_path)
            # sheets = word_book.sheetnames
            sheet_df = pd.read_excel(table_path, sheet_name=table, header=0, engine='openpyxl')
            print(sheet_df)
            sheet_df.to_excel(origin_file, sheet_name=table, index=False)
            logger.info(f"合并文件：{table_path}，sheet：{table}")
        logger.info(f"文件合并完成，输出文件：{origin_table}")
        return origin_table


if __name__ == '__main__':
    login_params = {'username': 'lijk34925', 'password': ''}
    os.chdir('../')
    flow = FlowReportObject()
    # flow.load_config()
    # flow.download_tables(login_params)
    # target_tables = ["测试进度统计报表", "JIRA缺陷统计（测试人员）", "缺陷类需求分析报表（产品维度）"]
    target_tables = ["测试进度统计报表"]
    flow.merge_tables(origin_table="./templates/EXCELMODULE.xlsx", target_tables=target_tables)
